/**
 * Copyright (C), 2020, Y2 T205
 * FileName: GuliFeignConfig
 * Author: Lenovo
 * Date: 2020-05-27 21:47
 * Description:
 * History:
 * <author> <time> <version> <desc>
 * 作者姓名 修改时间 版本号 描述
 */


package com.atguigu.gulimall.order.config;


import feign.RequestInterceptor;
import feign.RequestTemplate;
import feign.template.Template;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 〈一句话功能简述〉<br>
 * 〈〉
 *
 * @author Lenovo
 * @create 2020-05-27
 * @since 1.0.0
 */
//处理feign的远程调用丢失请求头，失去cookie的问题，丢失用户信息造成的错误
    @Configuration
public class GuliFeignConfig {

        @Bean("requestInterceptor")
        public RequestInterceptor requestInterceptor(){
            return new RequestInterceptor() {
                @Override
                public void apply(RequestTemplate requestTemplate) {
//                        1.RequestContextHolder 拿到刚进来的这个请求
                    ServletRequestAttributes attributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
                    if(attributes!=null){
                        HttpServletRequest request = attributes.getRequest();  //老请求

                        System.out.println("feign远程之前进行RequestInterceptor。aply");
                        if(request!=null){
                            //                    同步请求头cookie
                            String cookie = request.getHeader("Cookie");
//                    给新请求同步老请求
                            requestTemplate.header("Cookie",cookie);
                        }
                    }



                }
            };
        }


}
